#coding:utf-8
__author__ = 'dong'

#tcp client
#不支持中文
#2015.9.24

from PyQt4.QtGui import *
from PyQt4.QtCore import *
from myui import Ui_Form
from PyQt4.QtNetwork import *
import sys

class mainUi(QWidget, Ui_Form):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.setupUi(self)
        self.socket = QTcpSocket()
        # 以下是信号
        self.connect(self.pushButton_connect, SIGNAL('clicked()'), self.connectSlot)    # 连接
        self.connect(self.pushButton_clear, SIGNAL('clicked()'), self.clearSlot)        # 清空
        self.connect(self.pushButton_send, SIGNAL('clicked()'), self.sendSlot)          # 发送
        self.socket.readyRead.connect(self.readFromServer)
        self.socket.disconnected.connect(self.serverStopped)
        self.connect(self.socket, SIGNAL("error(QAbstractSocket::SocketError)"),self.serverError)

    # 连接
    def connectSlot(self):
        # 判断当前连接状态
        if self.socket.waitForConnected():      # 连接状态
            self.serverStopped()
            self.textBrowser_recv.append(u'断开连接')
            self.pushButton_connect.setText(u'连接')
        else:
            ip = self.lineEdit_ip.text()
            port = self.lineEdit_port.text()
            self.socket.connectToHost(ip, int(port))
            # 判断连接结果
            if self.socket.waitForConnected():
                self.textBrowser_recv.append(u'连接成功')
                self.pushButton_connect.setText(u'断开')
            else:
                self.textBrowser_recv.append(u'连接失败')

    # 清空
    def clearSlot(self):
        self.textBrowser_recv.clear()

    # 发送
    def sendSlot(self):
        msg = self.lineEdit_send.text()
        ch_msg = str(msg)
        self.socket.write(ch_msg)

    # 接收
    def readFromServer(self):
        msg = self.socket.readAll()
        self.textBrowser_recv.append(QString(msg))

    # 关闭
    def serverStopped(self):
        self.socket.close()

    #打印错误信息
    def serverError(self):
        self.textBrowser_recv.append("Error:{}".format(self.socket.errorString()))
        self.socket.close()
        self.pushButton_connect.setText(u'连接')

if __name__=="__main__":
    app = QApplication(sys.argv)
    mainui = mainUi()
    mainui.show()
    sys.exit(app.exec_())